<script setup>
import { ref, onMounted } from 'vue'
import easyapi from '../api'
import { ElMessageBox, ElMessage } from 'element-plus'
import axios from 'axios'
import dayjs from 'dayjs'

// 数据绑定
const allData = ref([])
const tableData = ref([])

// 分页状态
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)

// 通用数据刷新函数
const refreshData = async () => {
    try {
        const result = await easyapi.get('/api/user/all')
        if (Array.isArray(result.data)) {
            allData.value = result.data
            total.value = allData.value.length
            paginate()
        } else {
            console.error('API 返回的数据格式不正确')
        }
    } catch (error) {
        ElMessage({
            type: 'error',
            message: '数据加载失败: ' + (error.response?.data?.message || '未知错误'),
        })
    }
}

// 挂载页面时查询数据
onMounted(refreshData)

// 分页计算
const paginate = () => {
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    tableData.value = allData.value.slice(start, end)
}

// 处理分页变化
const handlePageChange = (newPage) => {
    currentPage.value = newPage
    paginate()
}

// 删除
const del = async (index, row) => {
    try {
        await ElMessageBox.confirm(
            "确定要删除该员工吗?",
            "提示框",
            {
                confirmButtonText: "确认",
                cancelButtonText: "取消",
                type: 'warning',
            }
        )
        await easyapi.del(`/api/user/del/${row.id}`);
        tableData.value.splice(index, 1);
        ElMessage({
            type: 'success',
            message: '删除成功',
        });
    } catch (error) {
        // 用户取消操作或者删除失败
        console.error('删除操作失败:', error)
    }
}

// 编辑
const editWinVisible = ref(false)
const editObject = ref({})

const edit = (index, row) => {
    editObject.value = { ...row }
    editWinVisible.value = true
}

const closeEditWin = () => {
    editWinVisible.value = false
}

const editSave = async () => {
    try {
        if (editObject.value.birthday) {
            editObject.value.birthday = dayjs(editObject.value.birthday).format('YYYY-MM-DDTHH:mm:ss')
        }
        await easyapi.putJson(`/api/user/edit/${editObject.value.id}`, editObject.value)
        ElMessage({
            type: 'success',
            message: '保存成功',
        })
        await refreshData()
        editWinVisible.value = false
    } catch (error) {
        ElMessage({
            type: 'error',
            message: `保存失败: ${error.response?.data?.message || '未知错误'}`,
        })
    }
}

// 新增
const addWinVisible = ref(false)
const addObject = ref({})

const openAddWin = () => {
    addObject.value = {}
    addWinVisible.value = true
}

const closeAddWin = () => {
    addWinVisible.value = false
}

const rulesRef = ref(null);
const addSave = async () => {
    rulesRef.value.validate(async(valid)=>{
        if(valid){
            try {
        if (addObject.value.birthday) {
            addObject.value.birthday = dayjs(addObject.value.birthday).format('YYYY-MM-DDTHH:mm:ss')
        }
        await easyapi.postJson('/api/user/add', addObject.value)
        ElMessage({
            type: 'success',
            message: '新增成功',
        })
        await refreshData()
        addWinVisible.value = false
    } catch (error) {
        ElMessage({
            type: 'error',
            message: '新增失败: ' + (error.response?.data?.message || '未知错误'),
        })
    }
        }else{
            ElMessage.error('请检查表单填写是否正确:'); 
        }
    })
    
}

// 查询
const query = ref('')

async function searchUser(keyword, isdel = null, isshelf = null) {
    try {
        const response = await axios.get('/api/user/search', {
            params: { keyword, isdel, isshelf }
        })
        allData.value = response.data.data
        total.value = allData.value.length
        paginate()
    } catch (error) {
        ElMessage({
            type: 'error',
            message: '查询失败: ' + (error.response?.data?.message || '未知错误'),
        })
    }
}

const searchProducts = () => {
    searchUser(query.value)
}

const resetSearchData = () => {
    query.value = ''
    searchUser('', 0, 0)
}
// // 头像加载失败
// const handleImageError = (event) => {
//     event.target.src = 'path/to/default-image.png' // 使用默认图像的路径
//     ElMessage({
//         type: 'error',
//         message: '图片加载失败',
//     })
// }

</script>

<template>
    <el-input 
        v-model="query" 
        placeholder="输入用户名或真实姓名进行查询" 
        @change="searchProducts" 
        style="flex: 1; max-width: 300px; height: 40px;" 
        size="medium"
        clearable/>

    <el-button type="primary" @click="searchProducts" size="medium">查询</el-button>
    <el-button type="warning" @click="resetSearchData" size="medium">重置</el-button>
    <el-button type="success" size="medium" @click="openAddWin">新增员工</el-button>

    <el-table :data="tableData" style="width: 100%">
        <el-table-column label="序号" width="80">
            <template v-slot="scope">
                {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
            </template>
        </el-table-column>
        
        <el-table-column label="头像" width="100">
    <template v-slot="scope">
        <el-image
            :src="`http://localhost:8080/user/image/${scope.row.id}`"
            fit="cover"
            style="width: 80px; height: 80px;"
            @error="handleImageError"
        />
    </template>
</el-table-column>


        <el-table-column prop="user_name" label="用户名" width="80" />
        <el-table-column prop="role_name" label="管理权限" width="80" />
<!--    <el-table-column label="管理权限" width="80">
            <template #default="scope">
                <span>{{ scope.row.class_id === 1 ? '管理员' : '用户' }}</span>
            </template>
        </el-table-column> -->
        <el-table-column prop="real_name" label="真实姓名" width="80" />
        <el-table-column prop="sex" label="性别" width="60" />
        <el-table-column prop="phone" label="电话" width="120" />
        <el-table-column prop="birthday" label="出生日期" min-width="80" />
        <el-table-column label="操作">
            <template #default="scope">
                <el-button type="warning" @click="edit(scope.$index, scope.row)">编辑</el-button>
                <el-button type="danger" @click="del(scope.$index, scope.row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>

    <el-pagination
        background
        layout="prev, pager, next"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        @current-change="handlePageChange">
    </el-pagination>

    <el-dialog v-model="editWinVisible" title="编辑" width="500">
        <el-form :model="editObject">
            <el-form-item label="用户名" label-width="80">
                <el-input v-model="editObject.user_name" autocomplete="off" />
            </el-form-item>
            <el-form-item label="真实姓名" label-width="80">
                <el-input v-model="editObject.real_name" autocomplete="off" />
            </el-form-item>
            <el-form-item label="性别" label-width="80">
                <el-input v-model="editObject.sex" autocomplete="off" />
            </el-form-item>
            <el-form-item label="电话" label-width="80">
                <el-input v-model="editObject.phone" autocomplete="off" />
            </el-form-item>
            <el-form-item label="管理权限" label-width="80">
                <el-select v-model="editObject.role_id" placeholder="请选择">
                    <el-option label="用户" :value="0" />
                    <el-option label="管理员" :value="1" />
                </el-select>
            </el-form-item>
            <el-form-item label="出生日期" label-width="80">
                <el-date-picker
                    v-model="editObject.birthday"
                    type="datetime"
                    placeholder="选择日期时间"
                    style="width: 100%;"
                />
            </el-form-item>
        </el-form>
        <!-- 弹窗底部按钮 -->
        <template #footer>
            <div class="dialog-footer">
                <!-- <el-button type="success" @click="openUploadWin">上传头像</el-button> -->
                <el-button @click="closeEditWin">取消</el-button>
                <el-button type="primary" @click="editSave">保存</el-button>
            </div>
        </template>
    </el-dialog>

    <el-dialog v-model="addWinVisible" title="新增员工" width="500">
        <el-form :model="addObject" :rules="rules" ref="rulesRef">

            <el-form-item label="用户名" label-width="80" prop="user_name" :rules="[{ required: true, message: '请输入用户名', trigger: 'blur' }]">
                <el-input v-model="addObject.user_name" autocomplete="off" />
            </el-form-item>
            <el-form-item label="密码" label-width="80" prop="password" :rules="[{ required: true, message: '请输入销售商名', trigger: 'blur' }]">
                <el-input v-model="addObject.password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="真实姓名" label-width="80" prop="real_name" :rules="[{ required: true, message: '请输入销售商名', trigger: 'blur' }]">
                <el-input v-model="addObject.real_name" autocomplete="off" />
            </el-form-item>
            <el-form-item label="性别" label-width="80" prop="sex" :rules="[{ required: true, message: '请输入销售商名', trigger: 'blur' }]">
                <el-input v-model="addObject.sex" autocomplete="off" />
            </el-form-item>
            <el-form-item label="电话" label-width="80" prop="phone" :rules="[{ required: true, message: '请输入销售商名', trigger: 'blur' }]">
                <el-input v-model="addObject.phone" autocomplete="off" />
            </el-form-item>
            <el-form-item label="管理权限" label-width="80" prop="role_id" :rules="[{ required: true, message: '请输入销售商名', trigger: 'blur' }]">
                <el-select v-model="addObject.role_id" placeholder="请选择">
                    <el-option label="用户" :value="0" />
                    <el-option label="管理员" :value="1" />
                </el-select>
            </el-form-item>
            <el-form-item label="出生日期" label-width="80" prop="birthday" :rules="[{ required: true, message: '请输入销售商名', trigger: 'blur' }]">
                <el-date-picker
                    v-model="addObject.birthday"
                    type="datetime"
                    placeholder="选择日期时间"
                    style="width: 100%;"
                />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <!-- <el-button type="success" @click="openUploadWin">上传头像</el-button> -->
                <el-button @click="closeAddWin">取消</el-button>
                <el-button type="primary" @click="addSave">保存</el-button>
            </div>
        </template>
    </el-dialog>

</template>

<style scoped>
.main-container {
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
.dialog-footer {
  text-align: right;
}
</style>
